package com.yc.test.Singleton;

/**
 * @Date: 2018/11/30 16:37
 * @Author: Can.Yang
 * @Description:懒汉式，线程不安全
 */
public class Singleton {
    private static Singleton singleton;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (singleton == null) {
            return new Singleton();
        }
        return singleton;
    }
}

/**
 * 懒汉式，线程安全
 */
class Singleton1 {
    private static Singleton1 singleton1;

    private Singleton1() {
    }

    public static synchronized Singleton1 getInstance() {
        if (singleton1 == null) {
            return new Singleton1();
        }
        return singleton1;
    }
}

/**
 * 饿汉式，线程安全
 */
class Singleton2 {
    private static Singleton2 singleton2 = new Singleton2();

    private Singleton2() {
    }

    public static Singleton2 getInstance() {
        return singleton2;
    }
}

/**
 * 双检锁，线程安全
 */
class Singleton3 {
    private volatile static Singleton3 singleton3;

    private Singleton3() {
    }

    public static Singleton3 getInstance() {
        if (singleton3 == null) {
            synchronized (Singleton3.class) {
                if (singleton3 == null) {
                    singleton3 = new Singleton3();
                }
            }
        }
        return singleton3;
    }
}

/**
 * 登记式/静态内部类，线程安全
 */
class Singleton4 {
    private static class SingletonHolder {
        private static final Singleton4 singleton4 = new Singleton4();
    }

    private Singleton4() {
    }

    public static final Singleton4 getInstance() {
        return SingletonHolder.singleton4;
    }
}

/**
 * 枚举，线程安全
 */
enum Singleton5 {
    Instance;

    public void whateverMethod() {
    }
}
